# -*- coding: UTF-8 -*-
# !/usr/bin/env python
# !/bin/sh

from __future__ import division
import os, sys
import numpy as np
import Image

try:
    import cStringIO as StringIO
except:
    import StringIO

file_path = os.path.dirname(__file__)
sys.path.append(file_path)
sys.path.append(os.path.join(file_path, 'tessdata'))

PICS_PATH = os.path.dirname(__file__)
PICS_PATH = '/'.join(PICS_PATH.split('/')[:-1]) + '/pics'

reload(sys)
sys.setdefaultencoding('utf-8')


def remove_noise(filename_1, filename_2, filename_3):
    string_io_1 = StringIO.StringIO(filename_1)
    string_io_2 = StringIO.StringIO(filename_2)
    string_io_3 = StringIO.StringIO(filename_3)
    im_c_1 = Image.open(string_io_1).convert('L')
    im_c_2 = Image.open(string_io_2).convert('L')
    im_c_3 = Image.open(string_io_3).convert('L')
    # x_size, y_size = im_c_1.shape
    # print np.array(im_c_1).shape
    x_size, y_size = (40, 260)
    im_c_1 = np.array(im_c_1).reshape(x_size * y_size, 1)
    im_c_2 = np.array(im_c_2).reshape(x_size * y_size, 1)
    im_c_3 = np.array(im_c_3).reshape(x_size * y_size, 1)
    th = 230
    for idx, vv in enumerate(im_c_1.tolist()):
        # print vv
        if vv[0] <= th and im_c_2[idx][0] <= th and im_c_3[idx][0] <= th:
            im_c_1[idx][0] = 255
        else:
            im_c_1[idx][0] = 1

    im_c_1 = im_c_1.reshape(40, 260)
    tmp_img = Image.fromarray(im_c_1)
    f = StringIO.StringIO()
    tmp_img.save(f, "BMP")
    img = f.getvalue()
    return img


if __name__ == '__main__':
    filename_1 = '/home/hy/gz_img/1.jpg'
    filename_2 = '/home/hy/gz_img/2.jpg'
    filename_3 = '/home/hy/gz_img/3.jpg'

    res = remove_noise(filename_1, filename_2)
    res = np.array(res)
    import cv2

    cv2.namedWindow("8")
    cv2.imshow("8", res)
    cv2.waitKey(0)
